package com.speily.current.volatileTest;

/**
 * @Auther: SPL
 * @Date: 2019-08-16 14:33
 * @Description: -多线程 Volatile变量运算，不安全
 */
public class UnsafeVolatileCountTest {

    volatile static int num = 0;

//    volatile static int num = 0;
//    static byte[] lock = new byte[0];

    static void count() {
        num++;
    }

    public static void threadTest() throws InterruptedException {



        Thread[] threads = new Thread[20];
        for (int i = 0; i < 20; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++)
//                    synchronized (lock){//这货线程不安全，锁上就行了
                        count();
//                    }
            });

            threads[i].start();
        }

        /*while(Thread.activeCount() > 1){
            Thread.yield();
        }*/
        Thread.sleep(2000L);
        System.out.println(num);
    }

    public static void main(String[] args) throws InterruptedException {


        for (int i = 0;i < 5;i++) {
            threadTest();
        }
    }
}
